package com.meaningful.Incurable_diseases;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipAutoEncodingDetector {

    private static final List<Charset> ENCODINGS = Arrays.asList(
            StandardCharsets.UTF_8,
            Charset.forName("GBK"),
            Charset.forName("GB18030"),
            Charset.forName("GB2312"),
            StandardCharsets.ISO_8859_1,
            Charset.forName("Windows-1252"),
            Charset.forName("Cp850")
    );

    public static void main(String[] args) throws IOException {
        File zipFile = new File("D:\\workspace\\meaningful_java_code\\thinking\\src\\main\\resources\\relocation3.zip");
        Charset detected = detectCharset(zipFile);

        if (detected != null) {
            System.out.println("检测到编码: " + detected.name());
            readZipWithCharset(zipFile, detected);
        } else {
            System.out.println("无法识别编码，尝试默认编码");
            readZipWithCharset(zipFile, StandardCharsets.UTF_8);
        }
    }

    private static Charset detectCharset(File zipFile) {
        for (Charset encoding : ENCODINGS) {
            // 从Java7开始，`ZipInputStream`的构造函数允许传入一个`Charset`对象。因此，我们可以尝试使用不同的字符集（如GBK）来读取ZIP文件
            // 在创建`ZipInputStream`时，传入一个特定的字符集（例如GBK）来避免UTF-8解码失败
            try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile), encoding)) {
                while (zis.getNextEntry() != null) ; // 尝试遍历条目
                return encoding; // 成功读取则返回编码
            } catch (Exception ignored) {
                // 尝试下一个编码
            }
        }
        return null;
    }

    private static void readZipWithCharset(File zipFile, Charset charset) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile), charset)) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                System.out.println(entry.getName());
                // 这里可以添加文件内容处理逻辑
            }
        }
    }

}
